﻿using MySql.Data.MySqlClient;
using System;
using System.Collections.Generic;
using System.Data.Common;
using System.Data.SqlClient;
using System.Linq;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace SassModule
{

    public class ConnCache
    {
        public static List<ConnectionString> ConnectionStrings { get; set; }
        public static string GetConnStr(string name=null)
        {
            if (ConnectionStrings!=null && ConnectionStrings.Count>0)
            {
                if (name==null)
                {
                    return ConnectionStrings[0].ConnectionStr;
                }
                return ConnectionStrings.FirstOrDefault(x => x.Name == name).ConnectionStr;
            }
            else
            {
                return null;
            }
        }
        public static DbConnection GetConn(string name=null)
        {
            if (ConnectionStrings == null || ConnectionStrings.Count <= 0) return null;
            string connStr = string.Empty;
            ConnectionString conn = ConnectionStrings.FirstOrDefault(x => x.Name ==name);
            if (conn==null)
            {
                conn = ConnectionStrings.FirstOrDefault(x => x.Extend);
                if (!string.IsNullOrEmpty(name))
                {
                    connStr = Regex.Replace(conn.ConnectionStr, "Database=.+?;", $"Database={name};", RegexOptions.None);
                }
                else
                {
                    connStr = conn.ConnectionStr;
                }
            }
            else
            {
                connStr = conn.ConnectionStr;
            }
            return (conn.DBType.ToLower()) switch
            {
                "sqlserver" => new SqlConnection(connStr),
                "mysql" => new MySqlConnection(connStr),
                _ => null,
            };
        }
    }
    public class ConnectionString
    {
        public string Name { get; set; }

        public string ConnectionStr { get; set; }

        public string DBType { get; set; }

        public bool Extend { get; set; }
    }
}
